package com.zl.registration.service.impl;

import com.zl.registration.dao.ActivityInfoDao;
import com.zl.registration.entity.ActivityInfo;
import com.zl.registration.mapper.ActivityInfoMapper;
import com.zl.registration.module.result.CodeMsg;
import com.zl.registration.service.RedisService;
import com.zl.registration.service.SignUpService;
import com.zl.registration.util.UUIDUtil;
import com.zl.registration.vo.SignUpVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 报名接口
 *
 * @author zoulei
 * @date 2021/12/6 17:52
 */
@Slf4j
@Service
public class SignUpServiceImpl implements SignUpService {

    @Resource
    private RedisService redisService;

    @Resource
    private ActivityInfoDao activityInfoDao;

    @Resource
    private ActivityInfoMapper activityInfoMapper;

    @Override
    public CodeMsg signUp(SignUpVo signUpInfo) {
        // 加锁操作 TODO 此步加锁不够高效，后期需要优化
        String uniqueValue = UUIDUtil.uuid() + "_" + Thread.currentThread().getId();
        String lockKey = "redis-lock" + signUpInfo.getActivityId();
        boolean lock = redisService.lock(lockKey, uniqueValue, 60 * 1000);
        if (!lock) {
            return CodeMsg.WAIT_SIGN_UP_DONE;
        }
        log.info("{}活动报名接口加锁成功", signUpInfo.getActivityId());

        // 检查用户是否已经报名此活动
        Map<String,Object> selectMap = new HashMap<>(8);
        selectMap.put("phone", signUpInfo.getPhone());
        selectMap.put("activityId", signUpInfo.getActivityId());
        List<ActivityInfo> activityInfos = activityInfoMapper.selectByMap(selectMap);
        if (!activityInfos.isEmpty()) {
            return CodeMsg.SIGN_UP_ALREADY;
        }
        // TODO 生成报名信息


        // TODO 写入数据库


        // 解锁
        boolean unLock = redisService.unlock(lockKey, uniqueValue);
        if (!unLock) {
            return CodeMsg.SIGN_UP_FAIL;
        }
        log.info("{}活动报名接口解锁成功", signUpInfo.getActivityId());

        // TODO 用户报名成功判断响应
        boolean success = true;
        if (success) {
            return CodeMsg.SIGN_UP_SUCCESS;
        }


        return CodeMsg.SIGN_UP_FAIL;
    }
}
